import matplotlib.pyplot as plt
import numpy as np

#中文
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

def demonstrate_one_sided_derivatives():
    """演示单侧导数的几何意义"""
    x_left = np.linspace(-2, 0, 100)
    x_right = np.linspace(0, 2, 100)
    f = lambda x: np.abs(x)
    
    # 计算左右导数
    left_derivative = -1  # 左导数
    right_derivative = 1   # 右导数
    
    plt.figure(figsize=(12, 5))
    
    # 函数图像
    plt.subplot(1, 2, 1)
    plt.plot(x_left, f(x_left), 'b-', linewidth=2, label='f(x) = |x|')
    plt.plot(x_right, f(x_right), 'b-', linewidth=2)
    
    # 左右切线
    x_tangent_left = np.linspace(-1, 0, 50)
    left_tangent = left_derivative * x_tangent_left
    plt.plot(x_tangent_left, left_tangent, 'r--', linewidth=2, 
             label=f'左切线: 斜率 = {left_derivative}')
    
    x_tangent_right = np.linspace(0, 1, 50)
    right_tangent = right_derivative * x_tangent_right
    plt.plot(x_tangent_right, right_tangent, 'g--', linewidth=2, 
             label=f'右切线: 斜率 = {right_derivative}')
    
    plt.scatter([0], [0], color='red', s=100, zorder=5)
    plt.title('绝对值函数在x=0处的左右导数')
    plt.xlabel('x')
    plt.ylabel('f(x)')
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.axis([-2, 2, -0.5, 2])
    
    # 另一个例子：分段函数
    plt.subplot(1, 2, 2)
    x1 = np.linspace(-1, 1, 100)
    g = lambda x: np.piecewise(x, [x < 0, x >= 0], [lambda x: x**2, lambda x: x])
    
    plt.plot(x1, g(x1), 'purple', linewidth=2, label='分段函数')
    
    # 在x=0处的左右导数
    g_left_deriv = 0  # (x²)' = 2x, 在x=0处为0
    g_right_deriv = 1  # (x)' = 1
    
    x_left_tangent = np.linspace(-0.5, 0, 50)
    left_tangent_g = g_left_deriv * x_left_tangent
    plt.plot(x_left_tangent, left_tangent_g, 'r--', linewidth=2, 
             label=f'左导数 = {g_left_deriv}')
    
    x_right_tangent = np.linspace(0, 0.5, 50)
    right_tangent_g = g_right_deriv * x_right_tangent
    plt.plot(x_right_tangent, right_tangent_g, 'g--', linewidth=2, 
             label=f'右导数 = {g_right_deriv}')
    
    plt.scatter([0], [0], color='red', s=100, zorder=5)
    plt.title('分段函数在x=0处的可导性')
    plt.xlabel('x')
    plt.ylabel('g(x)')
    plt.legend()
    plt.grid(True, alpha=0.3)
    
    plt.tight_layout()
    plt.show()

demonstrate_one_sided_derivatives()